package com.vercon.commonmirror.component;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import com.vercon.commonmirror.R;

import java.util.Timer;
import java.util.TimerTask;


/**
 * 自定义提示框
 */
public class MirrorToastComponent implements IToastComponent {
    private final Context context;
    private Toast toast;

    public MirrorToastComponent(Context context) {
        this.context = context;
    }

    @Override
    public void error(String message) {
        toast(message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void error(String message, int time) {
        showMyToast(toast(message, Toast.LENGTH_SHORT),time);
    }

    @Override
    public void success(String message) {
        toast(message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void success(String message, int time) {
        toast(message, time).show();
    }

    @Override
    public void debug(String message) {
        toast(message, Toast.LENGTH_SHORT).show();
    }

    public Toast toast(String message, int length) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.layout_toast, null);
        TextView messageTV = view.findViewById(R.id.tv_toast);
        messageTV.setText(message);
        toast = new Toast(context.getApplicationContext());
        toast.setGravity(Gravity.CENTER | Gravity.TOP, 0, 20);
        toast.setDuration(length);
        toast.setView(view);
        return toast;
    }

    public void showMyToast(final Toast toast, final int cnt) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        }, 0, 1000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt);
    }
}
